// 车辆处理函数模块

const db = require('../mysql/index')
const commonFunction = require('../common/common')
const fs = require('fs')
const path = require('path')


// 添加车辆
exports.carAdd = (req, res) => {
    for (const key in req.body) {
        if (req.body[key] === undefined) {
            req.body[key] = ''
        }
    }
    req.body.car_attr = JSON.stringify(JSON.parse(req.body.car_attr))
    let { brand_id, parking_id, model, number, vin, engineNum, checked, date, nextDate, gears, energy, emass, omass, km, mRent, dRent, hRent, enable, car_image, car_desc, car_attr } = req.body
    if (car_desc === '请输入正文') car_desc === ''
    enable == 'true' ? enable = 1 : enable = 0
    const arr = [brand_id, parking_id, model, number, vin, engineNum, checked, date, nextDate, gears, energy, emass, omass, km, mRent, dRent, hRent, enable, car_image, car_desc, car_attr]
    const s = 'INSERT into car(brand_id, parking_id, model, number, vin, engineNum, checked, date, nextDate, gears, energy, emass, omass, km, mRent, dRent, hRent, enable, car_image, car_desc, car_attr) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'
    db.query(s, arr, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('添加车辆失败')
        return res.send({
            code: 200,
            message: '添加车辆成功'
        })
    })
}

// 获取车辆列表
exports.getCarList = (req, res) => {
    let { pageNumber, pageSize, area, gears, enable, brandName } = req.body
    // 每页大小和偏移量
    pageSize = Number(pageSize)
    const offset = (Number(pageNumber) - 1) * pageSize
    // 有无其余参数的标志
    let flag = false
    // 可能需要提交的字段
    let paramsObj = {
        brand_name_ch: brandName,
        enable,
        gears,
        area
    }
    let paramsSql = 'SELECT car.id, number, brand_name_ch, model, brand_logo, car_image, checked, energy, car.enable, gears, parkingName, area, address FROM car, brand, parking WHERE brand_id = brand.id and parking_id = parking.id and '
    // 对sql进行参数处理
    const paramsArr = []
    const paramsValue = []
    for (const key in paramsObj) {
        const obj = {}
        if (paramsObj[key] !== undefined && paramsObj[key] !== '') {
            // 对布尔值和字符串的数字进行处理
            if (paramsObj[key] == 'true') { paramsObj[key] = 1 }
            if (paramsObj[key] == 'false') { paramsObj[key] = 0 }
            obj[key] = paramsObj[key]
            paramsArr.push(obj)
            flag = true
        }
    }
    paramsArr.forEach((item, index) => {
        if (index === paramsArr.length - 1) {
            if (item.brand_name_ch) {
                paramsSql += Object.keys(item) + ' like "%' + item[Object.keys(item)] + '%"'
            } else {
                if (item.enable == '1' || item.enable == '0') {
                    paramsSql += 'car.' + Object.keys(item) + '= ?'
                } else {
                    paramsSql += Object.keys(item) + '= ?'
                }
                paramsValue.push(item[Object.keys(item)])
            }
        } else {
            // 模糊查询
            if (item.brand_name_ch) {
                paramsSql += Object.keys(item) + ' like "%' + item[Object.keys(item)] + '%" and '
            } else {
                if (item.enable == '1' || item.enable == '0') {
                    paramsSql += 'car.' + Object.keys(item) + ' = ? and '
                } else {
                    paramsSql += Object.keys(item) + ' = ? and '
                }
                paramsValue.push(item[Object.keys(item)])
            }
        }
    });
    // 无参
    if (!flag) {
        const sql = 'SELECT car.id, number, brand_name_ch, model, brand_logo, car_image, checked, energy, car.enable, gears, parkingName, area, address FROM car, brand, parking WHERE brand_id = brand.id and parking_id = parking.id'
        db.query(sql, (err, result) => {
            if (err) return res.cc(err)
            if (result.length === 0) return res.send({ code: 201, message: '车辆列表为空' })
            // 将省市区代码转换为中文
            let counter = 0;
            result.forEach(async item => {
                const areaArr = item.area.split(',')
                const areaName = await commonFunction.getCityName(areaArr)
                item.area = areaName[0]
                item.enable === 1 ? item.enable = true : item.enable = false
                item.brand_logo = 'http://62.234.193.89:3007/' + item.brand_logo
                item.car_image = 'http://62.234.193.89:3007/' + item.car_image
                item.region = item.area + item.address;
                if (item.region.slice(0, 2) === item.region.slice(2, 4)) {
                    item.region = item.region.slice(2, item.region.length);
                }
                counter++;
                if (counter === result.length) {
                    let data = result.slice(offset, offset + pageSize)
                    return res.send({
                        code: 200,
                        message: '获取车辆列表成功',
                        data,
                        total: result.length
                    })
                }
            })
        })
    } else {
        db.query(paramsSql, [...paramsValue], (err, result) => {
            if (err) return res.cc(err)
            if (result.length === 0) return res.send({ code: 201, message: '未查询到车辆' })
            // 将省市区代码转换为中文
            let counter = 0;
            result.forEach(async item => {
                const areaArr = item.area.split(',')
                const areaName = await commonFunction.getCityName(areaArr)
                item.area = areaName[0]
                item.enable === 1 ? item.enable = true : item.enable = false
                item.brand_logo = 'http://62.234.193.89:3007/' + item.brand_logo
                item.car_image = 'http://62.234.193.89:3007/' + item.car_image
                item.region = item.area + item.address;
                if (item.region.slice(0, 2) === item.region.slice(2, 4)) {
                    item.region = item.region.slice(2, item.region.length);
                }
                counter++;
                if (counter === result.length) {
                    let data = result.slice(offset, offset + pageSize)
                    return res.send({
                        code: 200,
                        message: '获取车辆列表成功',
                        data,
                        total: result.length
                    })
                }
            })
        })
    }
}

// 删除车辆
exports.carDelete = (req, res) => {
    const id = req.query.id
    // 删除车辆图片
    const selectSql = 'SELECT car_image FROM car WHERE id = ?'
    db.query(selectSql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 1) {
            // 删除文件
            fs.unlink(path.join('./uploads', result[0].car_image), (err2) => {
                if (err2) console.log(err2);
            })
        }
    })
    // 删除车辆信息
    const deleteSql = 'DELETE FROM car WHERE id = ?'
    db.query(deleteSql, id, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('删除车辆失败')
        return res.send({
            code: 200,
            message: '删除车辆成功'
        })
    })
}

// 修改禁启用状态
exports.changeEnable = (req, res) => {
    const id = req.query.id
    const enable = req.query.enable === 'true' ? 1 : 0
    const sql = 'UPDATE car set enable = ? WHERE id = ?'
    db.query(sql, [enable, id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('修改状态失败')
        return res.send({
            code: 200,
            message: '修改状态成功'
        })
    })
}

// 获取车辆详情
exports.getCarDetaik = (req, res) => {
    const id = req.query.id
    const sql = 'SELECT * FROM car WHERE id = ?'
    db.query(sql, id, async (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('获取车辆详情失败')
        // 处理返回的结果
        let data = JSON.parse(JSON.stringify(result[0]))
        data.car_image = 'http://62.234.193.89:3007/' + data.car_image
        data.car_attr = JSON.parse(data.car_attr)
        data.enable = data.enable ? true : false
        return res.send({
            code: 200,
            message: '获取车辆详情成功',
            data
        })
    })
}

// 编辑车辆信息
exports.carEdit = (req, res) => {
    for (const key in req.body) {
        if (req.body[key] === undefined) {
            req.body[key] = ''
        }
    }
    req.body.car_attr = JSON.stringify(JSON.parse(req.body.car_attr))
    let { brand_id, parking_id, model, number, vin, engineNum, checked, date, nextDate, gears, energy, emass, omass, km, mRent, dRent, hRent, enable, car_image, car_desc, car_attr, id } = req.body
    if (car_desc === '请输入正文') car_desc === ''
    enable == 'true' ? enable = 1 : enable = 0
    const car_image_arr = car_image.split('/')
    car_image = car_image_arr[car_image_arr.length - 1]
    const arr = [brand_id, parking_id, model, number, vin, engineNum, checked, date, nextDate, gears, energy, emass, omass, km, mRent, dRent, hRent, enable, car_image, car_desc, car_attr, id]
    const s = 'UPDATE car set brand_id = ?, parking_id = ?, model = ?, number = ?, vin = ?, engineNum = ?, checked = ?, date = ?, nextDate = ?, gears = ?, energy = ?, emass = ?, omass = ?, km = ?, mRent = ?, dRent = ?, hRent = ?, enable = ?, car_image = ?, car_desc = ?, car_attr = ? WHERE id = ?'
    db.query(s, arr, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('修改车辆失败')
        return res.send({
            code: 200,
            message: '修改车辆成功'
        })
    })
}

// 获取车辆属性
exports.getCarAttr = (req, res) => {
    let { attr_key, attr_value } = req.body
    let sql = 'SELECT car_attr FROM car'
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 0) return res.cc('属性列表为空')
        let data = []
        result.forEach(item => {
            data.push(...JSON.parse(item.car_attr))
        })
        let arr = []
        if (attr_key) {
            arr = data.filter(item => item.attr_key === attr_key)
        } else if (attr_value) {
            arr = data.filter(item => item.attr_value === attr_value)
        } else arr = data
        if (arr.length === 0) return res.send({
            code: 201,
            message: '属性列表为空',
            data: arr
        })
        return res.send({
            code: 200,
            message: '获取车辆属性成功',
            data: arr
        })
    })
}

// 获取已启用的品牌列表
exports.getBrandList = (req, res) => {
    const sql = 'SELECT id, brand_name_ch from brand where status = 1'
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        return res.send({
            code: 200,
            message: '获取车辆品牌成功',
            data: result
        })
    })
}

// 获取已启用的停车场列表
exports.getParkingList = (req, res) => {
    const sql = 'SELECT id, parkingName from parking where enable = 1'
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        return res.send({
            code: 200,
            message: '获取停车场列表成功',
            data: result
        })
    })
}



// web端
// 获取停车场的车辆列表
exports.getCarsInParking = (req, res) => {
    const parking_id = req.query.parking_id
    const sql = 'SELECT car.id, number, model, car_image, energy, emass, omass, km, mRent, hRent, dRent, brand_logo, parkingName FROM car, brand, parking WHERE parking.id = parking_id and parking_id = ? and brand_id = brand.id and car.enable = 1 and subscribe = 0 GROUP BY car.id'
    db.query(sql, parking_id, (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 0) return res.send({ code: 200, message: '车辆列表为空', data: []})
        result.forEach(item => {
            item.car_image = 'http://62.234.193.89:3007/' + item.car_image
            item.brand_logo = 'http://62.234.193.89:3007/' + item.brand_logo
        })
        return res.send({
            code: 200,
            message: '获取车辆列表成功',
            data: result
        })
    })
}